<template>
    <div :style="props.with">
      <Toolbar v-if="props.isshowtools" style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="simple" />
      <Editor style="height: 500px; overflow-y: hidden" v-model="valueHtml" :defaultConfig="editorConfig" mode="simple" @onCreated="handleCreated" @customPaste="customPaste" />
      <el-button v-if="props.isshowtools" type="primary" @click="submit">提交</el-button>
    </div>
</template>

<script setup>
// 富文本编辑器文档链接: https://www.wangeditor.com/v5/getting-started.html
// 引入富文本编辑器CSS
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
import {createarticle} from "../../apis/article";
// 导入富文本编辑器的组件
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import axios from "axios"
const props = defineProps({
  with: {
    type: String,
    default: '100%'
  },
  isshowtools: {
    type: Boolean,
    default: false
  },
  isdisabled: {
    type: Boolean,
    default: false
  },
  content: {
    type: String,
    default: '<p>hello world</p>'
  }
})
// onMounted(()=>{
//   // 内容 HTML
//   console.log(props.content, '传进来的zhi');
// })
const valueHtml = ref('');
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig = {};
const editorConfig = ref({ placeholder: '请输入内容...', MENU_CONF: {} });

// 自定义图片上传
editorConfig.value.MENU_CONF['uploadImage'] = {
  async customUpload(file, insertFn) {
    console.log('上传图片', file);
    // 将上传的file图片转换为base64
    const base64 = URL.createObjectURL(file);
    // 这里的file为上传的图片对象,insertFn传入
    insertFn(base64, 'img');
  },
}
// 富文本编辑器生成后触发
const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  if (props.isdisabled) {
    editorRef.value.disable()
  }
  console.log(editorConfig.value.MENU_CONF, 'editorConfig.value');
};
// 监听富文本编辑器粘贴行为
const customPaste = (editor, event, callback) => {
  // 获取粘贴的纯文本
  const text = event.clipboardData.getData('text/plain');
  if (text) {
    editor.insertText(text);
    event.preventDefault();
    callback(false);
  }
};
const submit = () => {
  const text = {
    content: editorRef.value.getHtml() + '',
    title: '测试富文本'
  }
  // console.log('dianjile submit', editorRef.value.getHtml());
  createarticle(text).then((res)=>{
    console.log(res.data, 'data', text)
  })
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
watch(() => props.content, (newData, oldData) => {  
  if (newData !== oldData) {  
    valueHtml.value = props.content
  }  
})
</script>
